//////////////////////////////////////////////////////////////////////////////
//                                                                          //
//     Filename: BaccaratXMLTranslator.cpp                                  //
//  Create date: February 9, 2006                                           //
//                                                                          //
//////////////////////////////////////////////////////////////////////////////
//                                                                          //
//  Description: This file implements the BaccaratXMLTranslator class.      //
//               This class is a protocol translator that translates from   //
//               the RTG Baccarat protocol to XML and back.                 //
//                                                                          //
//////////////////////////////////////////////////////////////////////////////
//       Copyright (c) 2004 - Realtime Gaming.  All rights reserved.        //
//////////////////////////////////////////////////////////////////////////////

#include <windows.h>
#include <stdio.h>
#include "lib.h"
#include "BaccaratXMLTranslator.h"
#include "XMLDoc.h"
#include "endian.h"
#include "log.h"
#include "card.h"

//////////////////////////////////////////////////////////////////////////////
// Constructor
//////////////////////////////////////////////////////////////////////////////
BaccaratXMLTranslator::BaccaratXMLTranslator( Server* pServer, Connection* pParent ) : 
                                             XMLTranslator( pServer, pParent, 0, 1 )
{
}

//////////////////////////////////////////////////////////////////////////////
// Destructor
//////////////////////////////////////////////////////////////////////////////
BaccaratXMLTranslator::~BaccaratXMLTranslator()
{
}

//////////////////////////////////////////////////////////////////////////////
// TranslateIncomingMessage
//////////////////////////////////////////////////////////////////////////////
bool8 BaccaratXMLTranslator::TranslateIncomingMessage( uint8* pGameInBuff,  
												 uint32 nGameInBuffSize, 
												 uint8* pOutBuff, 
												 uint32 nOutBuffSize )
{
    bool8 bRetVal = false;

	// Handle the messages.  Note, I'm only going to look at the first character
	//  in a small attempt to optimize a bit
	switch( m_sMsgID[0] )
	{
		case 'L':
			bRetVal = TranslateInLogin( m_pDoc, pGameInBuff, nGameInBuffSize );
			break;

		case 'B':
			bRetVal = TranslateInBalance( m_pDoc, pGameInBuff, nGameInBuffSize, GetNumBytesMsgLen() );
			break;

		case 'D':
			bRetVal = TranslateInDeal( m_pDoc, pGameInBuff, nGameInBuffSize );
			break;

		default:
			String sMsg = TEXT("Error, received unknown client message: ");
			sMsg += m_sMsgID;
			Log::msgError( sMsg );
			break;
	}

	// Report Error
	if( !bRetVal )
	{
		if ( m_sMsgID[0] == 'L' )
		{
			// Set an error into the out buffer
			ReturnLoginError( pOutBuff, nOutBuffSize );
		}
		else
		{
			// Set an error into the out buffer
			ReturnErrorMessage( TEXT("ServerError"), pOutBuff, nOutBuffSize );

			String sMsg = TEXT("Error translating incoming message: ");
			sMsg += m_sMsgID;
			Log::msgError( sMsg );
		}
	}

	return bRetVal;
}

//////////////////////////////////////////////////////////////////////////////
// TranslateOutgoingMessage
//////////////////////////////////////////////////////////////////////////////
uint32 BaccaratXMLTranslator::TranslateOutgoingMessage( uint8* pOutBuff, 
												  uint32 nOutBuffSize, 
												  uint8* pGameOutBuff, 
												  uint32 nGameOutBuffSize, 
												  uint32 nTotalGameBytes    )
{
	bool8 bResult = true;
	uint32 nGameBytesUsed = 0;
	uint32 nOutBytesUsed = 0;

	while ( bResult && (nGameBytesUsed < nTotalGameBytes) )
	{
		// Keep track of buffers as we might be processing more than one game
		//   message at a time.
		uint8* pCurGameBuf     = pGameOutBuff     + nGameBytesUsed;
		uint32 nCurGameBufSize = nGameOutBuffSize - nGameBytesUsed;
		uint8* pCurOutBuf      = pOutBuff         + nOutBytesUsed;
		uint32 nCurOutBufSize  = nOutBuffSize     - nOutBytesUsed;

		// Make sure buffer has not been overrun!
		if ( nOutBytesUsed > nOutBuffSize )
		{
			ASSERT(false);
			Log::msgError( "Error, out buffer overflow!" );
			return 0;
		}

		// Now the actual message handlers!
		switch( pCurGameBuf[1] )
		{
			case 'L':
				bResult = TranslateOutLogin( pCurOutBuf, nCurOutBufSize, pCurGameBuf, nCurGameBufSize );
				break;
			
			case 'm':
				bResult = TranslateOutBalance( pCurOutBuf, nCurOutBufSize, pCurGameBuf, nCurGameBufSize, 1 );
				break;

			case 'D':
				bResult = TranslateOutDeal( pCurOutBuf, nCurOutBufSize, pCurGameBuf, nCurGameBufSize );
				break;

			case 'E':
				bResult = TranslateGenericOutError( pCurOutBuf, nCurOutBufSize, pCurGameBuf, nCurGameBufSize, 1 );
				break;

			case 'C':
			case 'N':
			case 'G':
			case 'b':
			case 'l':
			case '$':
			case '!':
				bResult = TranslateOutError( pCurOutBuf, nCurOutBufSize, pCurGameBuf, nCurGameBufSize );
				break;

			default:
				bResult = ReturnErrorMessage( TEXT("UnknownMessage"), pCurOutBuf, nCurOutBufSize );
				Log::msgError( "Received unknown game message: %c", pCurGameBuf[1] );
				break;
		}

		// Check and see if any errors occurred
		if ( !bResult )
		{
			ReturnErrorMessage( TEXT("ParseError"), pCurOutBuf, nCurOutBufSize );
			Log::msgError( "Error translating outgoing message: %c", pCurGameBuf[1] );
		}

		// We know that the size of the message is always stored in the first
		//  byte of the client message.
		nGameBytesUsed += pCurGameBuf[0];

		// Out XML Messages are supposed to be NULL Terminated
		nOutBytesUsed += strlen( (char*) pCurOutBuf );
		nOutBytesUsed++;  // Add one for the NULL

		DEBUGMSG( ("\n***Outgoing: %s", pCurOutBuf) );
	}

	return nOutBytesUsed;
}

//****************************************************************************
// Internal Helpers
//****************************************************************************

//////////////////////////////////////////////////////////////////////////////
// AddHandStructure
//////////////////////////////////////////////////////////////////////////////
bool8 BaccaratXMLTranslator::AddHandStructure( XMLDoc* pDoc, 
										 const String& sParentQuery, 
										 uint8* pBuff, 
										 uint8& nNumBytesUsed )
{
	// num cards
	uint8 nNumCards = pBuff[nNumBytesUsed++];
	if ( !pDoc->AddChildNode( sParentQuery, TEXT("num_cards"), (uint32) nNumCards ) )
	{
		return false;
	}

	// the actual cards
	for( uint8 i = 0; i < nNumCards; i++ )
	{
		String sText;
		sText.sprintf( TEXT("card_%d"), i );

		// Get Card value
		Card c;
		nNumBytesUsed += (uint8) c.deSerialize( pBuff + nNumBytesUsed );

		if ( !pDoc->AddChildNode( sParentQuery, sText, c ) )
		{
			return false;
		}
	}

	return true;
}

//****************************************************************************
// Incoming
//****************************************************************************

//////////////////////////////////////////////////////////////////////////////
// TranslateInLogin
//////////////////////////////////////////////////////////////////////////////
bool8 BaccaratXMLTranslator::TranslateInLogin( XMLDoc* pDoc, uint8* pGameInBuff, uint32 nGameInBuffSize )
{
	////////////////////////////////////////////////////////////////
	// Login the user
	////////////////////////////////////////////////////////////////
    if ( !LoginUser( pDoc ) )
    {
        return false;
    }

	// Start by skipping the first byte of the message, that will be the
	//  length
	uint32 nOffset = 1;

	////////////////////////////////////////////////////////////////
	// Write Login for Baccarat
	////////////////////////////////////////////////////////////////
	pGameInBuff[nOffset++] = 'M';
	pGameInBuff[nOffset++] = 'L';
	pGameInBuff[nOffset++] = 'B';
	pGameInBuff[nOffset++] = 'r';

	////////////////////////////////////////////////////////////////
	// Add Version Info
	////////////////////////////////////////////////////////////////
	if ( !AddLoginVersionInfo( nOffset, pDoc, pGameInBuff ) )
	{
		return false;
	}

	////////////////////////////////////////////////////////////////
	// Add ID
	////////////////////////////////////////////////////////////////
	if ( !AddLoginID( nOffset, pDoc, pGameInBuff ) )
	{
		return false;
	}
    
	////////////////////////////////////////////////////////////////
	// play for money/play for fun
	////////////////////////////////////////////////////////////////
	if ( !AddLoginMoneyType( nOffset, pDoc, pGameInBuff ) )
	{
		return false;
	}

	////////////////////////////////////////////////////////////////
	// Cient type: CSN-7534
	////////////////////////////////////////////////////////////////
	if ( !AddClientID( nOffset, pDoc, pGameInBuff ) )
	{
		return false;
	}

	////////////////////////////////////////////////////////////////
	// Authentication token. CSN-7075: New Authentication
	////////////////////////////////////////////////////////////////
	if ( !AddAuthenticationToken( nOffset, pDoc, pGameInBuff ) )
	{
		return false;
	}

    ////////////////////////////////////////////////////////////////
	// Finally, add message size
	////////////////////////////////////////////////////////////////
	pGameInBuff[0] = (uint8) nOffset;

	return true;
}

//////////////////////////////////////////////////////////////////////////////
// TranslateInDeal
//////////////////////////////////////////////////////////////////////////////
bool8 BaccaratXMLTranslator::TranslateInDeal( XMLDoc* pDoc, uint8* pGameInBuff, uint32 nGameInBuffSize )
{

	uint8 nMsgSize = 1;

	pGameInBuff[nMsgSize++] = 'D';

	uint32 nBetOnBanker = 0;
	pDoc->GetSingleNodeLong( TEXT("//bet_on_banker"), nBetOnBanker );
	Endian::SendInt4( nBetOnBanker, pGameInBuff + nMsgSize );
	nMsgSize +=4 ;

	uint32 nBetOnPlayer = 0;
	pDoc->GetSingleNodeLong( TEXT("//bet_on_player"), nBetOnPlayer );
	Endian::SendInt4( nBetOnPlayer, pGameInBuff + nMsgSize );
	nMsgSize +=4 ;

	uint32 nBetOnTie = 0;
	pDoc->GetSingleNodeLong( TEXT("//bet_on_tie"), nBetOnTie );
	Endian::SendInt4( nBetOnTie, pGameInBuff + nMsgSize );
	nMsgSize +=4 ;

	// Finally, write the size of the message
	pGameInBuff[0] = nMsgSize;

	return true;
}


//****************************************************************************
// Outgoing
//****************************************************************************

//////////////////////////////////////////////////////////////////////////////
// TranslateOutError
//////////////////////////////////////////////////////////////////////////////
bool8 BaccaratXMLTranslator::TranslateOutError( uint8* pOutBuff, 
										  uint32 nOutBuffSize, 
										  uint8* pGameOutBuff, 
										  uint32 nGameOutBuffSize )
{
	bool8 bRetVal = false;

	if ( pGameOutBuff[1] == '$' )
	{
		bRetVal = ReturnErrorMessage( TEXT("InsufficientFunds"), pOutBuff, nOutBuffSize );
	}
	else if ( pGameOutBuff[1] == 'G' )
	{
		bRetVal = ReturnErrorMessage( TEXT("InProgress"), pOutBuff, nOutBuffSize );
	}
	else if ( pGameOutBuff[1] == 'N' )
	{
        // kharmon.  02-21-07.  MCA #29819.  Need to send back different messages for auto and admin logoffs.
        String strErrorName = "InvalidLogin";

        if(pGameOutBuff[0]==6)  // The extra 4 bytes have the error code.
        {
            int32 nErrorCode=0;
            Endian::ReceiveInt4( &nErrorCode, &pGameOutBuff[2] );

            switch(nErrorCode)
            {
                case TrackSQL::AdminLogout:
                {
                    strErrorName = "AdminLogout";
                    break;
                }
                case TrackSQL::AutoLogout:
                {
                    strErrorName = "TimedOut";
                    break;
                }
            }            
        }

        bRetVal = ReturnErrorMessage( strErrorName, pOutBuff, nOutBuffSize );
	}
	else if ( pGameOutBuff[1] == 'b' )
	{
		bRetVal = ReturnErrorMessage( TEXT("InvalidBet"), pOutBuff, nOutBuffSize );
	}
	else if ( pGameOutBuff[1] == 'l' )
	{
		bRetVal = ReturnErrorMessage( TEXT("NoLogin"), pOutBuff, nOutBuffSize );
	}
	else if ( pGameOutBuff[1] == '!' )
	{
		bRetVal = ReturnErrorMessage( TEXT("Shutdown"), pOutBuff, nOutBuffSize );
	}
	else if ( pGameOutBuff[1] == 'C' )
	{
		bRetVal = ReturnErrorMessage( TEXT("SettingsChanged"), pOutBuff, nOutBuffSize );
	}

	return bRetVal;
}

//////////////////////////////////////////////////////////////////////////////
// TranslateOutLogin
//////////////////////////////////////////////////////////////////////////////
bool8 BaccaratXMLTranslator::TranslateOutLogin( uint8* pOutBuff, 
										  uint32 nOutBuffSize, 
										  uint8* pGameOutBuff, 
										  uint32 nGameOutBuffSize )
{
	XMLDoc doc;

	if ( !doc.StartNew() )
	{
		return false;
	}

	if ( !doc.CreateRootNode( TEXT("game_msg") ) )
	{
		return false;
	}

	if ( !doc.AddRootChildNode( TEXT("msg_id"), TEXT("Login") ) )
	{
		return false;
	}

	// Balance 
	int32 nValue;
	Endian::ReceiveInt4( &nValue, pGameOutBuff+2 );
	if ( !doc.AddRootChildNode( TEXT("balance"), (uint32) nValue ) )
	{
		return false;
	}

	// Minimum Bet
	Endian::ReceiveInt4( &nValue, pGameOutBuff+6 );
	if ( !doc.AddRootChildNode( TEXT("min_bet"), (uint32) nValue ) )
	{
		return false;
	}

	// Maximum Bet
	Endian::ReceiveInt4( &nValue, pGameOutBuff+10 );
	if ( !doc.AddRootChildNode( TEXT("max_bet"), (uint32) nValue ) )
	{
		return false;
	}

	// Tie Payout Odds
	Endian::ReceiveInt4( &nValue, pGameOutBuff+14 );
	if ( !doc.AddRootChildNode( TEXT("tie_payout"), (uint32) nValue ) )
	{
		return false;
	}

	if ( !AddCurrencyOutput(&doc) )	// CSN-11204: return currency
	{
		return false;
	}

	// Done - send the actual XML
	if ( !doc.SendXML( pOutBuff, nOutBuffSize ) )
	{
		return false;
	}

	return true;
}

//////////////////////////////////////////////////////////////////////////////
// TranslateOutDeal
//////////////////////////////////////////////////////////////////////////////
bool8 BaccaratXMLTranslator::TranslateOutDeal( uint8* pOutBuff, 
									     uint32 nOutBuffSize, 
									     uint8* pGameOutBuff, 
									     uint32 nGameOutBuffSize )
{
	XMLDoc doc;

	if ( !doc.StartNew() )
	{
		return false;
	}

	if ( !doc.CreateRootNode( TEXT("game_msg") ) )
	{
		return false;
	}

	if ( !doc.AddRootChildNode( TEXT("msg_id"), TEXT("Deal") ) )
	{
		return false;
	}

	// Banker Hand
	const String sBanker = TEXT("banker_hand");
	if ( !doc.AddRootChildNode( sBanker ) )
	{
		return false;
	}
	
	uint8 nBytesUsed = 2;
	const String sRootQuery = TEXT("//");
	String sBankerQuery = sRootQuery;
	sBankerQuery += sBanker;
	if ( !AddHandStructure( &doc, sBankerQuery, pGameOutBuff, nBytesUsed ) )
	{
		return false;
	}

	// Dealer Hand
	const String sPlayer = TEXT("player_hand");
	if ( !doc.AddRootChildNode( sPlayer ) )
	{
		return false;
	}
	
	String sPlayerQuery = sRootQuery;
	sPlayerQuery += sPlayer;
	if ( !AddHandStructure( &doc, sPlayerQuery, pGameOutBuff, nBytesUsed ) )
	{
		return false;
	}

	// Banker Payout
	int32 nValue;
	Endian::ReceiveInt4( &nValue, pGameOutBuff+nBytesUsed );
	nBytesUsed += 4;
	if ( !doc.AddRootChildNode( TEXT("banker_payout"), (uint32) nValue ) )
	{
		return false;
	}

	// Player Payout
	Endian::ReceiveInt4( &nValue, pGameOutBuff+nBytesUsed );
	nBytesUsed += 4;
	if ( !doc.AddRootChildNode( TEXT("player_payout"), (uint32) nValue ) )
	{
		return false;
	}

	// Tie Payout
	Endian::ReceiveInt4( &nValue, pGameOutBuff+nBytesUsed );
	nBytesUsed += 4;
	if ( !doc.AddRootChildNode( TEXT("tie_payout"), (uint32) nValue ) )
	{
		return false;
	}

	// Commission
	Endian::ReceiveInt4( &nValue, pGameOutBuff+nBytesUsed );
	nBytesUsed += 4;
	if ( !doc.AddRootChildNode( TEXT("commission"), (uint32) nValue ) )
	{
		return false;
	}

	// Use Commission
	bool8 use_commission = !!*(pGameOutBuff+nBytesUsed);
	nBytesUsed++;
	if ( !doc.AddRootChildNode( TEXT("use_commision"), use_commission ) )
	{
		return false;
	}

	// Winnings
	Endian::ReceiveInt4( &nValue, pGameOutBuff+nBytesUsed );
	nBytesUsed += 4;
	if ( !doc.AddRootChildNode( TEXT("winnings"), (uint32) nValue ) )
	{
		return false;
	}

	// Balance 
	Endian::ReceiveInt4( &nValue, pGameOutBuff+nBytesUsed );
	nBytesUsed += 4;
	if ( !doc.AddRootChildNode( TEXT("balance"), (uint32) nValue ) )
	{
		return false;
	}

	// Done - send the actual XML
	if ( !doc.SendXML( pOutBuff, nOutBuffSize ) )
	{
		return false;
	}

	return true;
}
